<template>
  <div class="book-list-container">
    <!-- Header Section -->
    <header class="main-header">
      <div class="header-content">
        <div class="logo">图书借阅中心</div>
        <nav class="main-nav">
          <ul>
            <li class="dropdown-parent" @mouseover="showCategoryDropdown = true" @mouseleave="showCategoryDropdown = false">
              <a href="#">分类</a>
              <ul class="dropdown-menu" v-if="showCategoryDropdown">
                <li @click="filterByCategory('所有分类')">所有分类</li>
                <li v-for="cat in categories" :key="cat.name" @click="filterByCategory(cat.name)">
                  {{ cat.name }}
                </li>
              </ul>
            </li>
            <li><a href="#" @click="goToBorrowedRecords">我的借阅</a></li>
            <li><a href="#" @click="handleContactNavigation">联系我们</a></li>
          </ul>
        </nav>
        <div class="header-right">
          <div class="search-bar">
            <input type="text" placeholder="搜索书名、作者或出版社" v-model="searchQuery" @keyup.enter="handleSearch" />
            <el-icon class="search-icon" @click="handleSearch"><Search /></el-icon>
          </div>
          <div class="user-cart-icons">
            <el-icon @click="goToUserProfile"><User /></el-icon>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
      <!-- Recommended Categories -->
      <section class="recommendation-section">
        <h3>为你推荐</h3>
        <div class="categories-row">
          <div class="category-tag" v-for="cat in recommendedCategories" :key="cat.name" @click="filterByCategory(cat.name)">
            {{ cat.name }}
          </div>
        </div>
      </section>

      <!-- Book List Section -->
      <section class="book-list-section">
        <div class="book-card" v-for="book in filteredBooks" :key="book.id" @click="goToBookDetail(book.id)">
          <img :src="book.coverImage" :alt="book.title" />
          <h3>{{ book.title }}</h3>
          <p class="author">{{ book.author }}</p>
          <span class="category-tag-small">{{ book.category }}</span>
          <p class="stock" :class="{ 'low-stock': book.stock <= 5 && book.stock > 0, 'no-stock': book.stock === 0 }">
            {{ book.stock > 0 ? `库存: ${book.stock}本` : '无库存' }}
          </p>
        </div>
        <div v-if="filteredBooks.length === 0" class="no-books-found">
          <el-empty description="没有找到相关书籍"></el-empty>
        </div>
      </section>
    </main>

    <!-- Book Detail Dialog -->
    <el-dialog
      v-model="bookDetailDialogVisible"
      title="书籍详情"
      width="60%"
      v-if="selectedBook"
    >
      <div class="book-detail-dialog-content">
        <div class="dialog-image">
          <img :src="selectedBook.coverImage" :alt="selectedBook.title" />
        </div>
        <div class="dialog-info">
          <h3>{{ selectedBook.title }}</h3>
          <p>作者: {{ selectedBook.author }}</p>
          <p>出版社: {{ selectedBook.publisher }}</p>
          <p>类别: {{ selectedBook.category }}</p>
          <p class="description">简介: {{ selectedBook.description }}</p>
          <p class="stock" :class="{ 'low-stock': selectedBook.stock <= 5 && selectedBook.stock > 0, 'no-stock': selectedBook.stock === 0 }">
            库存: {{ selectedBook.stock > 0 ? `${selectedBook.stock}本` : '无' }}
          </p>
          <div class="dialog-actions">
            <el-input-number v-model="borrowQuantity" :min="1" :max="selectedBook.stock > 0 ? selectedBook.stock : 0" :disabled="selectedBook.stock === 0" />
            <el-button type="primary" @click="handleBorrowBook(selectedBook)" :disabled="selectedBook.stock === 0">
              {{ selectedBook.stock === 0 ? '无库存' : '立即借阅' }}
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElDialog, ElInputNumber, ElEmpty } from 'element-plus'
import {
  Search,
  User,
  Reading,
  List // For borrowed records
} from '@element-plus/icons-vue'

const router = useRouter()

const searchQuery = ref('')
const showCategoryDropdown = ref(false)
const currentCategory = ref('所有分类')
const bookDetailDialogVisible = ref(false)
const selectedBook = ref(null)
const borrowQuantity = ref(1)

// 模拟书籍数据
const books = ref([
  {
    id: 1,
    title: 'Vue.js 权威指南',
    coverImage: 'https://via.placeholder.com/150x200?text=Vue.js+Guide',
    author: '前端老张',
    publisher: '编程出版社',
    category: '编程开发',
    description: '深入浅出Vue.js核心概念和最佳实践。',
    stock: 10
  },
  {
    id: 2,
    title: 'React Hooks 深度解析',
    coverImage: 'https://via.placeholder.com/150x200?text=React+Hooks',
    author: '技术小李',
    publisher: '电子工业出版社',
    category: '编程开发',
    description: '从原理到实践，全面掌握React Hooks。',
    stock: 5
  },
  {
    id: 3,
    title: '西湖风光摄影集',
    coverImage: 'https://via.placeholder.com/150x200?text=West+Lake+Photo',
    author: '摄影师王',
    publisher: '旅游出版社',
    category: '摄影艺术',
    description: '精选西湖四季美景，带你领略江南韵味。',
    stock: 3
  },
  {
    id: 4,
    title: 'Python 数据分析实战',
    coverImage: 'https://via.placeholder.com/150x200?text=Python+Data',
    author: '数据老王',
    publisher: '科学出版社',
    category: '数据科学',
    description: '从零开始，用Python进行数据清洗、分析与可视化。',
    stock: 8
  },
  {
    id: 5,
    title: '美食的诱惑',
    coverImage: 'https://via.placeholder.com/150x200?text=Food+Delight',
    author: '美食家李',
    publisher: '生活出版社',
    category: '生活百科',
    description: '探索全球美食文化，学习制作各种美味佳肴。',
    stock: 12
  },
  {
    id: 6,
    title: 'JavaScript 高级编程',
    coverImage: 'https://via.placeholder.com/150x200?text=JS+Advanced',
    author: '代码小陈',
    publisher: '编程出版社',
    category: '编程开发',
    description: '深入理解JavaScript高级特性，编写高质量代码。',
    stock: 0 // 模拟无库存
  },
]);

// 模拟书籍分类数据
const categories = ref([
  { name: '编程开发', icon: 'Code' },
  { name: '摄影艺术', icon: 'Camera' },
  { name: '数据科学', icon: 'TrendCharts' },
  { name: '生活百科', icon: 'Bowl' },
  { name: '历史文化', icon: 'Reading' },
  { name: '科幻小说', icon: 'Star' },
]);

// 模拟借阅记录（这将最终存储在 BookRecords.vue 中）
const borrowedRecords = ref([]);

// 模拟推荐分类 (基于用户习惯，这里为静态示例)
const recommendedCategories = computed(() => {
  // 实际项目中会根据用户借阅历史、浏览偏好等动态生成
  const habits = ['编程开发', '数据科学', '生活百科'];
  return categories.value.filter(cat => habits.includes(cat.name));
});

const filteredBooks = computed(() => {
  let filtered = books.value;

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(book =>
      book.title.toLowerCase().includes(query) ||
      book.author.toLowerCase().includes(query) ||
      book.publisher.toLowerCase().includes(query)
    );
  }

  if (currentCategory.value !== '所有分类') {
    filtered = filtered.filter(book => book.category === currentCategory.value);
  }

  return filtered;
});

const handleSearch = () => {
  console.log('Searching for:', searchQuery.value);
  // 搜索逻辑由 computed 属性 filteredBooks 处理
};

const filterByCategory = (categoryName) => {
  currentCategory.value = categoryName;
  showCategoryDropdown.value = false; // 点击分类后关闭下拉框
  console.log('Filtering by category:', categoryName);
};

const goToBorrowedRecords = () => {
  router.push('/credit/life/books/records');
};

const handleContactNavigation = () => {
  console.log('Navigate to Contact Us page');
};

const goToUserProfile = () => {
  router.push('/user/profile');
};

const goToBookDetail = (bookId) => {
  selectedBook.value = books.value.find(b => b.id === bookId);
  if (selectedBook.value) {
    bookDetailDialogVisible.value = true;
    borrowQuantity.value = 1; // 打开弹窗时重置数量
  }
};

const handleBorrowBook = (book) => {
  if (book.stock === 0) {
    ElMessage.warning('该书籍暂无库存，无法借阅。');
    return;
  }
  if (borrowQuantity.value > book.stock) {
    ElMessage.warning(`借阅数量不能超过库存（${book.stock}本）。`);
    return;
  }

  // 模拟借阅成功
  book.stock -= borrowQuantity.value; // 更新库存
  ElMessage.success(`成功借阅 《${book.title}》 x ${borrowQuantity.value} 本！`);
  
  // 将借阅信息添加到模拟的借阅记录中
  const existingRecord = borrowedRecords.value.find(record => record.bookId === book.id);
  if (existingRecord) {
    existingRecord.quantity += borrowQuantity.value;
    existingRecord.borrowDate = new Date().toLocaleDateString();
  } else {
    borrowedRecords.value.push({
      bookId: book.id,
      title: book.title,
      coverImage: book.coverImage,
      quantity: borrowQuantity.value,
      borrowDate: new Date().toLocaleDateString(),
      returnDate: '-'
    });
  }

  bookDetailDialogVisible.value = false; // 关闭弹窗
  console.log('当前借阅记录:', borrowedRecords.value);
  
  // 可以在这里跳转到借阅记录页面
  // router.push('/credit/life/books/records');
};

</script>

<style scoped>
.book-list-container {
  font-family: Arial, sans-serif;
  background-color: #f8f8f8;
  color: #333;
}

/* Header Styles - Copied from ShoppingList, adjust as needed */
.main-header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
  padding: 15px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.main-nav ul {
  list-style: none;
  display: flex;
  margin: 0;
  padding: 0;
}

.main-nav li a {
  text-decoration: none;
  color: #555;
  padding: 0 15px;
  font-weight: 500;
}

.main-nav li a:hover {
  color: #007bff;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-bar {
  position: relative;
  margin-right: 20px;
}

.search-bar input {
  border: 1px solid #ccc;
  border-radius: 20px;
  padding: 8px 15px 8px 35px;
  width: 250px;
  outline: none;
}

.search-bar .search-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  cursor: pointer;
}

.user-cart-icons .el-icon {
  font-size: 20px;
  margin-left: 15px;
  cursor: pointer;
  color: #555;
}

/* Dropdown Styles - Copied from ShoppingList */
.dropdown-parent {
  position: relative;
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  list-style: none;
  padding: 10px 0;
  margin-top: 10px;
  min-width: 120px;
  z-index: 1000;
}

.dropdown-menu li {
  padding: 8px 15px;
  cursor: pointer;
  white-space: nowrap;
  /* display: block; 保持竖直排列 */
}

.dropdown-menu li:hover {
  background-color: #f5f7fa;
  color: #007bff;
}

/* Main Content Styles */
.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* Recommendation Section */
.recommendation-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.recommendation-section h3 {
  margin-top: 0;
  color: #333;
  font-size: 20px;
  margin-bottom: 15px;
}

.categories-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tag {
  background-color: #e6f7ff;
  color: #007bff;
  padding: 8px 15px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.category-tag:hover {
  background-color: #007bff;
  color: #fff;
}

/* Book List Section */
.book-list-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); /* Adjust column size for book covers */
  gap: 20px;
}

.book-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 15px;
  text-align: center;
  transition: transform 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.book-card:hover {
  transform: translateY(-5px);
}

.book-card img {
  max-width: 100%;
  height: 200px; /* Consistent height for book covers */
  object-fit: cover; /* Use cover to fill space, might crop */
  border-radius: 4px;
  margin-bottom: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.book-card h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
  height: 40px; /* Limit height for title */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-card .author {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}

.book-card .category-tag-small {
  background-color: #f0f0f0;
  color: #777;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin-top: auto; /* Push to bottom */
}

.book-card .stock {
  font-size: 14px;
  color: #555;
  margin-top: 10px;
}

.book-card .stock.low-stock {
  color: #e6a23c; /* Warning yellow */
  font-weight: bold;
}

.book-card .stock.no-stock {
  color: #f56c6c; /* Danger red */
  font-weight: bold;
}

/* Book Detail Dialog Styles */
.book-detail-dialog-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.book-detail-dialog-content .dialog-image {
  flex-shrink: 0;
}

.book-detail-dialog-content .dialog-image img {
  width: 220px;
  height: 300px; /* Larger image in dialog */
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.dialog-info {
  flex: 1;
}

.dialog-info h3 {
  font-size: 28px;
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.dialog-info p {
  margin-bottom: 8px;
  color: #555;
  line-height: 1.6;
}

.dialog-info .description {
  font-size: 15px;
  color: #666;
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  border-left: 3px solid #007bff;
  margin-top: 20px;
  margin-bottom: 20px;
}

.dialog-actions {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 25px;
}
</style> 